<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use think\Db;
use think\Request;

class Activity extends Common {
    /**
     * @var mixed
     */
    public $params = null;
    /**
     * @param Request $request
     */
    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }

    /**
     * @return mixed
     */
    public function chatDiscountConfig() {
        $data = Db::name('act_chat_discount_config')->where(['id' => 1])->field('name,starttime,endtime,discount,description')->find();
        $hasJoin = Db::name('act_chat_discount_user')->where(['user_id' => $this->member['id'], 'state' => 0])->find();
        $data['joined'] = $hasJoin ? true : false;
        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function chatDiscountJoin() {
        $data = Db::name('act_chat_discount_config')->where(['id' => 1])->find();
        if (!$data) {
            return $this->miss('活动配置异常');
        }

        $timenow = time();
        if ($timenow < strtotime($data['starttime'])) {
            // return $this->miss('活动未开始');
        }
        if ($timenow > strtotime($data['endtime'])) {
            return $this->miss('活动已结束');
        }

        $hasJoin = Db::name('act_chat_discount_user')->where(['user_id' => $this->member['id'], 'state' => 0])->find();
        if ($hasJoin) {
            return $this->miss('已报名,无需重复报名');
        }
        $res = Db::name('act_chat_discount_user')->insert([
            'user_id'     => $this->member['id'],
            'starttime'   => $data['starttime'],
            'endtime'     => $data['endtime'],
            'discount'    => $data['discount'],
            'state'       => 0,
            'create_time' => $timenow,
        ]);
        if ($res) {
            return $this->pass('报名成功');
        }
        return $this->miss('报名失败,请重试');
    }

    public function chatDiscountExit()
    {
        $hasJoin = Db::name('act_chat_discount_user')->where(['user_id' => $this->member['id'], 'state' => 0])->find();
        if (!$hasJoin) {
            return $this->miss('未报名,无需退出');
        }
        $res = Db::name('act_chat_discount_user')
                ->where(['id'=>$hasJoin['id']])
                ->update([
                    'state'       => -2,
                    'expire_time' => time(),
                ]);
        if ($res) {
            return $this->pass('退出成功');
        }
        return $this->miss('退出失败,请重试');
    }
}